// 更新后的 PopupQuiz.tsx
import { fetchApi } from '@/request/request';
import { X } from 'lucide-react';
import React, { useEffect } from 'react';
import { useState } from 'react';
import { loadingToast, showToast } from '../ui/toast';
import { useRouter } from '@/utils/router';
import { usePlayStore } from '@/store/setPlayAudio';
import { poupp } from '../ui/popup';

interface questionType {
  id: string;
  type: 'multiple' | 'single';
  question: string;
  zh_question: string;
  options: Array<any>;
  details: {
    id: Array<number>;
    text: string
  };
  optionsList: any;
  level: number;
  questionList: Array<any>;
  answer: string | Array<number>;
  trans: boolean;
}

interface PopupQuizProps {
  openQuiz: boolean;
  onClose: () => void;
  setHighlight: (value: Array<number>) => void;
  article: { id: string, content: { id: number, text: string }[] }
}

interface AnswerType {
  id: string;
  correct: boolean;
  correctAnswer: Array<string>,
  selectedAnswer: Array<string> | "未选择";
  details: {
    id: Array<number>;
    text: string
  }
}

const PopupQuiz = ({ onClose, setHighlight, article, openQuiz }: PopupQuizProps) => {
  const router = useRouter()
  const { setPlayAudio } = usePlayStore();
  const [answer, setAnswer] = useState<AnswerType[] | []>([]);
  const [selectAnswers, setSelectAnswers] = useState<{ id: string, key: string[] }[]>([]);
  const [questions, setQuestions] = useState<questionType[] | []>([]);
  const [sureAnswer, setSureAnswer] = useState<Array<any>>([]) //答案

  //整理答案
  const processAnswers = (content: Array<questionType>) => {
    return content.map((e) => {
      setSureAnswer((prev) => [...prev, { id: e.id, type: e.type, answer: e.answer, details: e.details }]);//标准答案
      setSelectAnswers((prev) => {
        const exists = prev.some((item) => item.id === e.id);
        if (!exists) {
          return [...prev, { id: e.id, type: e.type, key: [] }];
        }
        return prev;
      });//用户答案模板

      return {
        ...e,
        questionList: e.question.split(" "),
        zh_question: '没有翻译',
        options: e.options.map((i) => {
          return {
            ...i,
            zh_value: "没有翻译",
            trans: false,
            valueList: i.value.split(" ")
          }
        }),
        trans: false,
      }
    })
  }

  useEffect(() => {
    if (!openQuiz) return;
    if (article.id) {
      fetchApi("/api/translate", { action: "quzzle", params: { chatID: article.id } })
        .then((res: any) => {
          setQuestions(processAnswers(res.data))
          if (res.data.length == 0) { // 没有题目,生成
            createQuzzle()
          }
        }).catch((error) => {
          showToast("加载失败，重试")
        })
    } else {
      showToast("加载失败，重试！")
    }
  }, [openQuiz])

  //ai生成内容
  const createQuzzle = () => {
    if (article) {
      loadingToast.open('');
      try {
        fetchApi("/api/translate", { action: "createQuzzle", params: { chatID: article.id, text: article.content } }).then((res: any) => {
          const data = processAnswers(res.data) as any
          setQuestions(data)
          loadingToast.close();
        })
      } catch (e) {
        loadingToast.close();
        showToast("加载失败，重试")
      }
    } else {
      showToast("题目刷新失败，退出重试")
    }
  }

  //翻译句子
  const handleTranslate = async (id: string, text: any, key: string) => {
    //翻译api
    const get_api = async (txt: string) => {
      const word = await fetchApi(`/api/translate`,
        { action: "translate", params: { "text": txt } }) as any;
      return word.data.text;
    }

    //翻译题目、选项
    if (Array.isArray(text)) {
      const txt = text.find((e) => e.key === key).value;
      const zh_text = await get_api(txt);
      setQuestions((prevState: any[]) =>
        prevState.map(item =>
          item.id === id
            ? {
              ...item, // 保留其他属性
              options: item.options.map((e: any) =>
                e.key === key ? { ...e, zh_value: zh_text, trans: true } : e
              ),
            } : item
        )
      );
    } else {
      const zh_text = await get_api(text);
      setQuestions((prevState: any[]) =>
        prevState.map(item =>
          item.id === id ? { ...item, zh_question: zh_text, trans: true } : item
        )
      );
    }
  }

  //某个单词
  const handleClick = async (e: React.MouseEvent, text: string) => {
    e.stopPropagation(); // 防止点击冒泡
    const userStr = localStorage.getItem('user') || "{}";
    const user = JSON.parse(userStr); // 👈 正确解析 JSON 字符串成对象
    const word = await fetchApi(`/api/translate`,
      { action: "word", params: { id: user.id, text } }) as any;
    const wordList = word.data;
    if (wordList != 0) {
      poupp(e, `
        <div style="max-width:200px;padding: 10px; border-radius: 8px; background: white; border: 1px solid #ccc; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);">
            ${wordList.map((item: { v: any; k: any; }) => `
            <div style="margin-bottom: 5px;">
                <div style="font-weight: bold;">${item.k}</div>
                <div style="color: gray;">${item.v}</div>
            </div>`).join('')}
        </div>`
      );
    } else { showToast("没有查询结果") }
    setPlayAudio([text]);
  };

  // 检查答案
  const checkAnswer = () => {
    if (answer.length > 0) {
      setAnswer([]); // 🔄 第二次点击清空
      setHighlight([])
    } else {
      const results = sureAnswer.map((answer) => {
        const selected = selectAnswers.find((sel) => sel.id === answer.id);

        if (selected) {
          // 确保 answer.key 和 selected.key 都是数组
          const correct = selected
            ? answer.answer.length === selected.key.length &&
            answer.answer.every((k: string) => selected.key.includes(k))
            : false;

          return {
            id: answer.id,
            correct,
            correctAnswer: answer.answer,
            selectedAnswer: selected.key.length > 0 ? selected.key : "未选择",
            details: answer.details
          };
        }
      }) as any

      setAnswer(results); // ✅ 第一次点击设置答案
    }
  };

  const select = (id: string, key: string, checked: boolean) => {

    setSelectAnswers((prev: any) =>
      prev.map((e: any) => {
        if (e.id !== id) return e; // 不是目标 ID，直接返回
        //多选
        if (e.type === "multiple") {
          return {
            ...e,
            key: checked
              ? [...(e.key || []), key] // ✅ 选中：添加 key
              : (e.key || []).filter((k: any) => k !== key), // ✅ 取消选中：移除 key
          };
        }
        return { ...e, key }; // 单选情况
      })
    );
  };

  const scrollToId = (id: string) => {
    const el = document.getElementById(id);
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 80; // 偏移 80 像素
      window.scrollTo({ top: y, behavior: 'smooth' });
    }
  };

  return (
    <div className='mt-2 '>
      {/* 退出按钮 */}
      <div onClick={onClose} className="fixed top-2 right-6 w-5">
        <button
          onClick={onClose}
          className="bg-red-500 rounded-full text-white text-2xl px-1"
        >
          <X />
        </button>
      </div>
      {/* 题目区域 */}
      {questions.map((q, index) => (
        <div key={`${index}-${q.id}`} className="mt-8 bg-[#ffffff] rounded-lg p-5">

          <div className="text-lg font-semibold mb-2 border-b-2 border-[#f9f9f9]" onClick={() => { handleTranslate(q.id, q.question, '') }}
            onDoubleClick={(event) => {
              event.stopPropagation(); // 阻止事件冒泡
              setPlayAudio([q.question]);
            }}>
            {index + 1}. {q.questionList.map((ql: any, qi: number) => {
              return <span key={`${qi}-${ql}`} onClick={(e) => { handleClick(e, ql) }}>{`${ql} `}</span>
            })}
            {q.type === 'single' ? '(单选)' : '(多选)'}
            <span className="ml-2 text-[14px] text-[#4c4c4c]">
              难度：{
                q.level === 1 ? '简单' :
                  q.level === 2 ? '普通' :
                    q.level === 3 || q.level == 4 ? '困难' :
                      q.level === 5 ? '地狱' : '未知'
              }
            </span>

            {q.trans && (<h2 className="text-lg font-semibold mb-2">{q.zh_question}</h2>)}
          </div>

          <div className="space-y-2 border-b-2 border-[#f9f9f9] mt-2">
            {q.options.map((option: any, optionIndex: number) => (

              <div key={`${option.key}i-${optionIndex}`} className="flex items-center">
                <label className="flex items-center" >
                  <input
                    type={q.type === 'single' ? 'radio' : 'checkbox'}
                    name={q.type === "single" ? `question${q.id}` : undefined} // 只有单选时才有 `name`
                    value={option.key}
                    onChange={(e) => select(q.id, option.key, e.target.checked)}
                  // onClick={() => { select() }}
                  />
                  {option.key}.
                </label>

                <span className="ml-2 flex items-center w-full" onClick={() => handleTranslate(q.id, q.options, option.key)}
                  onDoubleClick={(event) => {
                    event.stopPropagation(); // 阻止事件冒泡
                    setPlayAudio([option.value]);
                  }}>
                  <span className="ml-2">
                    {option.valueList.map((ov: any, ovi: number) => (
                      <span key={`${ov}-${ovi}`} onClick={(e) => { handleClick(e, ov) }}>{`${ov} `} </span>
                    ))}
                    {option.trans && (
                      <span className="mb-2">{option.zh_value}</span>
                    )}
                  </span>
                </span>
              </div>
            ))}
          </div>
          {answer.length > 0 && answer[index] && (
            <div className={`${answer[index]?.correct ? "text-[#00d26a]" : "text-red-500"}`}
              onClick={() => {
                scrollToId(`content-${answer[index].details.id[0]}`)
                setHighlight(answer[index].details.id)
              }}>
              <div>答案：{answer[index].correctAnswer}</div>
              <div>详情：{answer[index].details.text}</div>
            </div>)}
        </div>
      ))}

      <div className="flex justify-center items-center m-5">
        <div>
          <button
            className="px-4 py-2 bg-[#000000] text-white rounded hover:bg-[#4c4c4c] mr-2"
            onClick={() => {
              checkAnswer()
            }}
          >
            答案
          </button>
        </div>
        <div>
          <button
            className="px-4 py-2 bg-[#000000] text-white rounded hover:bg-[#4c4c4c] mr-2"
            onClick={() => { createQuzzle(); router.refresh() }}
          >
            更多题目
          </button>
        </div>
        {/* <div>
          <button
            className="px-4 py-2 bg-[#000000] text-white rounded hover:bg-[#4c4c4c] mr-2"
            onClick={() => {
              console.log('提交逻辑');
              onClose();
            }}
          >
            记录
          </button>
        </div> */}
      </div>
    </div>
  );
};


export default PopupQuiz;